package cn.xshi.actuator.util;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Desc 读取本地日志文
 * @Author 邓纯杰
 * @CreateTime 2013-10-05 17:15:42
 */
@Slf4j
public class LogReaderUtils {

	// 上次文件大小
	private static long lastTimeFileSize = 0;

	// 先进先出的 阻塞队列
	private static BlockingQueue blockingQueue = new LinkedBlockingQueue<>(10000);

	/**
	 * 实时读取日志
	 * @param actuatorLogPath
	 * @return
	 */
	public static String poll(String actuatorLogPath) {
		try {
			execute(actuatorLogPath);
			String msg = (String) blockingQueue.take();
			return msg;
		} catch (InterruptedException e) {
			log.debug("RuntimeExec异常：{}",e);
		}
		return null;
	}

	/**
	 * 执行read
	 * @param actuatorLogPath
	 */
	private static void execute(String actuatorLogPath) {
		File logFile = new File(actuatorLogPath);
		try {
			if(logFile.exists()){
				long len = logFile.length();
				if (len < lastTimeFileSize) {
					lastTimeFileSize = len;
				} else if (len > lastTimeFileSize) {
					RandomAccessFile randomAccessFile = new RandomAccessFile(logFile, "r");
					randomAccessFile.seek(lastTimeFileSize);
					String tmp = null;
					while ((tmp = randomAccessFile.readLine()) != null) {
						blockingQueue.add(new String(tmp.getBytes("ISO-8859-1"), "UTF-8"));
					}
					lastTimeFileSize = randomAccessFile.length();
					randomAccessFile.close();
				}
			}else{
				log.debug("日志不存在：{}",actuatorLogPath);
			}
		} catch (IOException e) {
			log.debug("RuntimeExec异常：{}",e);
		}
	}
}
